package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户API控制器
 * @author Logan.Li
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 用户登录 - 使用数据库BCrypt验证
     * 支持数据库中的用户：admin、super123等
     */
    @PostMapping("/login/")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginForm) {
        String username = loginForm.get("username");
        String password = loginForm.get("password");
        
        // 使用数据库验证
        User user = userService.authenticate(username, password);
        
        if (user != null) {
            Map<String, Object> data = new HashMap<>();
            // 生成JWT Token
            String token = jwtUtil.generateToken(
                user.getUsername(), 
                user.getEmail() != null ? user.getEmail() : "", 
                "admin"
            );
            data.put("token", token);
            data.put("username", user.getUsername());
            data.put("name", user.getNickname() != null ? user.getNickname() : user.getUsername());
            data.put("role", "admin");
            data.put("email", user.getEmail());
            return Result.success(data);
        } else {
            return Result.error("用户名或密码错误");
        }
    }
    
    /**
     * 获取用户信息
     */
    @GetMapping("/info/")
    public Result<Map<String, Object>> getUserInfo(@RequestHeader(value = "Authorization", required = false) String token) {
        // 验证JWT token
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                // 验证token并提取用户信息
                String username = jwtUtil.getUsernameFromToken(token);
                String email = jwtUtil.getEmailFromToken(token);
                String role = jwtUtil.getRoleFromToken(token);
                
                if (!jwtUtil.isTokenExpired(token)) {
                    Map<String, Object> userInfo = new HashMap<>();
                    userInfo.put("username", username);
                    userInfo.put("name", username);
                    userInfo.put("email", email);
                    userInfo.put("roles", new String[]{role});
                    return Result.success(userInfo);
                }
            } catch (Exception e) {
                return Result.error("Token无效：" + e.getMessage());
            }
        }
        return Result.error("未登录或token已过期");
    }
    
    /**
     * 退出登录
     */
    @PostMapping("/logout/")
    public Result<Void> logout() {
        // 实际项目中应清除服务端session或token记录
        return Result.success(null);
    }
    
    /**
     * 修改密码
     */
    @PostMapping("/changePassword/")
    public Result<String> changePassword(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String oldPassword = request.get("oldPassword");
        String newPassword = request.get("newPassword");
        
        if (username == null || oldPassword == null || newPassword == null) {
            return Result.error("参数不完整");
        }
        
        if (newPassword.length() < 6) {
            return Result.error("新密码长度不能少于6位");
        }
        
        // 验证旧密码
        User user = userService.authenticate(username, oldPassword);
        if (user == null) {
            return Result.error("原密码错误");
        }
        
        // 更新密码
        boolean success = userService.changePassword(username, newPassword);
        if (success) {
            return Result.success("密码修改成功");
        } else {
            return Result.error("密码修改失败");
        }
    }
    
    /**
     * 刷新Token
     */
    @PostMapping("/refresh/")
    public Result<Map<String, Object>> refreshToken(@RequestHeader(value = "Authorization", required = false) String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                String newToken = jwtUtil.refreshToken(token);
                Map<String, Object> data = new HashMap<>();
                data.put("token", newToken);
                return Result.success(data);
            } catch (Exception e) {
                return Result.error("Token刷新失败：" + e.getMessage());
            }
        }
        return Result.error("无效的Token");
    }
    
    /**
     * 获取用户列表
     */
    @GetMapping("/users/")
    public Result<Object> getUsers(@RequestHeader(value = "Authorization", required = false) String token) {
        // 验证JWT token
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                if (!jwtUtil.isTokenExpired(token)) {
                    // 简化处理，返回固定用户列表
                    Map<String, Object> data = new HashMap<>();
                    data.put("total", 2);
                    data.put("users", new String[]{"admin", "super123"});
                    return Result.success(data);
                }
            } catch (Exception e) {
                return Result.error("Token验证失败");
            }
        }
        return Result.error("未登录或token已过期");
    }
}
